package com.tange.module.share;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;

import com.tg.appcommon.android.ResourcesUtil;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGToast;
import com.tange.base.toolkit.ClipboardUtils;
import com.tg.data.http.entity.SimpleStatusBean;
import com.tange.core.backend.service.http.ClientObserver;
import com.tg.network.socket.http.TGHttp;

import java.util.HashMap;
import java.util.List;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 设备分享码 逻辑处理
 */
public class ShareCodeManager {

    private static final String TAG = "ShareCodeManager";

    /**
     * 分享码 示例
     * SC://473UT4L9S6B8:34:1653363575
     */
    private static final String SHARE_CODE_PREFIX = "SC://";
    private static final String SHARE_CODE_SPLIT = ":";
    private static final int SHARE_CODE_MIN_LENGTH = 12;

    private static volatile ShareCodeManager instance;

    /** 登录页的，临时存储 用完清理 */
    private String shareCodeCache;

    private TGAlertDialog alertDialog;

    private ShareCodeManager() { }

    public static ShareCodeManager getInstance() {
        if (instance == null) {
            synchronized (ShareCodeManager.class) {
                if (instance == null) {
                    instance = new ShareCodeManager();
                }
            }
        }
        return instance;
    }

    public void recognize(Activity activity) {
        recognize(activity, null, false, true, null);
    }

    public void recognize(Activity activity,
                          List<String> exitsUuids,
                          boolean addAfterClickDialogSure,
                          boolean ignoreShareCodeCache,
                          Runnable onAddSuccessRunnable) {

        if (isActivityDestroyed(activity) || activity == null || activity.getWindow() == null || activity.getWindow().getDecorView() == null) {
            TGLog.i(TAG, "recognize: activity == null or env not support");
            return;
        }

        activity.getWindow().getDecorView().post(() -> {

            TGLog.i(TAG, "recognize: ...");

            if (isActivityDestroyed(activity)) {
                TGLog.i(TAG, "recognize: activity destroyed.");
                return;
            }

            String pasteContent = null;

            if (!TextUtils.isEmpty(shareCodeCache)) {
                if (ignoreShareCodeCache) {
                    TGLog.i(TAG, "recognize: has share code cache , ignore it because in login process.");
                    return;
                }
                TGLog.i(TAG, "recognize: has share code cache , use it");
                addDevice(shareCodeCache, onAddSuccessRunnable);
                return;
            } else {
                pasteContent = ClipboardUtils.paste(activity);
                TGLog.i(TAG, "recognize: get content from clipboard");
            }

            if (TextUtils.isEmpty(pasteContent)) {
                TGLog.i(TAG, "recognize: empty clipboard.");
                return;
            }

            TGLog.i(TAG, "recognize: pasteContent = [" + pasteContent + "]");

            // 把用户可能不小心拷贝的空格、换行等，移除掉
            pasteContent = pasteContent.trim().replace("\n","");

            TGLog.i(TAG, "recognize: pasteContent (after fix) = [" + pasteContent + "]");

            // 1. 是否是 分享码，例如 SC://473UT4L9S6B8:34:1653363575
            if (!isShareCode(pasteContent)) {
                TGLog.i(TAG, "recognize: not a share code, skip");
                return;
            }

            // 2. 查询是否 "未被添加"：保存的uuid列表，没有这个uuid
            String tempStr = pasteContent.replace(SHARE_CODE_PREFIX, "");
            TGLog.i(TAG, "recognize: tempStr = " + tempStr);
            String[] tempStrArr = tempStr.split(SHARE_CODE_SPLIT);
            if (tempStrArr == null || tempStrArr.length < 1) {
                TGLog.i(TAG, "recognize: parsing error tempStrArr = null");
                return;
            }

            for (String str : tempStrArr) {
                TGLog.i(TAG, "recognize: tempStrArr item = " + str);
            }

            String uuid = tempStrArr[0];

            TGLog.i(TAG, "recognize: uuid = " + uuid);

            TGLog.i(TAG, "recognize: exitsUuids = " + exitsUuids);

            if (TextUtils.isEmpty(uuid)) {
                TGLog.i(TAG, "recognize: parsing error uuid null");
                ClipboardUtils.clear(activity);
                return;
            }

            if (exitsUuids != null && exitsUuids.size() > 0) {
                if (exitsUuids.contains(uuid)) {
                    TGLog.i(TAG, "recognize: already exist this device");
                    ClipboardUtils.clear(activity);
                    return;
                }
            }

            showDialog(activity, pasteContent, addAfterClickDialogSure, onAddSuccessRunnable);
        });
    }

    private void addDevice(String shareCode, Runnable onAddSuccessRunnable) {

        TGLog.i(TAG, "addDevice: ...");

        final HashMap<String, String> params = new HashMap<>();
        params.put("code", shareCode);

        TGLog.i(TAG, "addDevice: params = " + params);

        TGHttp.getInstance().verifyShareCode(params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ClientObserver<SimpleStatusBean>() {
                    @Override
                    protected void onSuccess(SimpleStatusBean content) {
                        TGLog.i(TAG, "addDevice onSuccess, refresh device list now ");
                        if (onAddSuccessRunnable != null) {
                            Handler h = new Handler(Looper.getMainLooper());
                            h.post(onAddSuccessRunnable);
                        }
                        shareCodeCache = "";
                    }

                    @Override
                    protected void onResponseError(int errorCode, String errorInfo) {
                        TGLog.i(TAG, "addDevice onResponseError  = " + errorCode + " , " + errorInfo);
                        TGToast.showToast(errorInfo);
                        shareCodeCache = "";
                    }

                    @Override
                    protected void onOtherError(String error) {
                        TGLog.i(TAG, "addDevice onOtherError " + error);
                        TGToast.showToast(error);
                        shareCodeCache = "";
                    }

                    @Override
                    public void onError(Throwable e) {
                        TGLog.i(TAG, "addDevice onError" + Log.getStackTraceString(e));
                        TGToast.showToast(e.getMessage());
                        shareCodeCache = "";
                    }

                    @Override
                    protected void onFinish() {
                        TGLog.i(TAG, "addDevice onFinish");
                    }
                });
    }

    private static boolean isShareCode(String code) {
        return !TextUtils.isEmpty(code) && code.startsWith(SHARE_CODE_PREFIX) && code.length() > SHARE_CODE_MIN_LENGTH;
    }

    private void showDialog(Activity activity,
                            String shareCode,
                            boolean addAfterClickDialogSure,
                            Runnable onAddSuccessRunnable) {

        if (isActivityDestroyed(activity)) return;

        dismissDialogIfNeeded();

        if (isActivityDestroyed(activity)) return;

        alertDialog = new TGAlertDialog(activity)
                .builder(R.layout.tange_dialog_receive_share_code)
                .setCancelable(false)
                .setMessage(ResourcesUtil.getString(addAfterClickDialogSure ? R.string.share_code_received_in_list : R.string.share_code_received_in_login))
                .setPositiveButton(ResourcesUtil.getString(addAfterClickDialogSure ? R.string.share_code_received_sure : R.string.share_code_received_sure_2), v -> {

                    if (addAfterClickDialogSure) {
                        TGLog.i(TAG, "dialog: click OK, add device now");
                        addDevice(shareCode, onAddSuccessRunnable);

                        shareCodeCache = "";
                    } else {
                        TGLog.i(TAG, "dialog: click OK, will add device after login");
                        shareCodeCache = shareCode;
                    }

                    ClipboardUtils.clear(activity);
                }).setNegativeButton(ResourcesUtil.getString(R.string.share_code_received_refuse), v -> {
                    TGLog.i(TAG, "dialog: click refuse , clear clipboard.");
                    ClipboardUtils.clear(activity);

                    if (addAfterClickDialogSure) {
                        shareCodeCache = "";
                    }
                });

        if (isActivityDestroyed(activity)) return;

        alertDialog.show();
    }

    private static boolean isActivityDestroyed(Activity activity) {
        return activity == null || activity.isDestroyed() || activity.isFinishing();
    }

    public void dismissDialogIfNeeded() {
        if (alertDialog != null && alertDialog.isShowing()) {
            alertDialog.dismiss();
        }
    }

}
